// pages/evaluateDetail/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    drugName:'',
    done:0,
    all:0,
    progross:0,
    disabled:true,
    newSubjectData:[],
    drugId:'',
    date:'',
    finished:false,
    coin:0,
    isNeedSave:false,
    userAnswerId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id){
      this.setData({
        finished: options.id == 'true'
      })
    }
    if (options.userAnswerId){
      this.data.userAnswerId = options.userAnswerId
    }
    // else{
    //   this.data.userAnswerId = 'cfeec955e9244c129cde0fc1256d5779'
    // }
  
    if (this.data.finished){
      this.setNewDataList(app.drugList.drugQuestionList)
      this.setData({
        coin: app.drugList.consultDrug.coin
      })
    }else{
      this.getDrugQuestionDetail()
    }
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    wx.getStorage({
      key: 'evaluateData',
      success: function(res) {
        console.log(res)
        // var data = 
        if(res.data){
          that.setData({
            newSubjectData: JSON.parse(res.data)
          })
          that.checkProgress()
        }
       
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('我消失了')
    if (this.data.isNeedSave){
      let data = JSON.stringify(this.data.newSubjectData)
      wx.setStorage({
        key: "evaluateData",
        data: data
      })
    }
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  // 获取题目详情
  getDrugQuestionDetail(){
    var that = this
    app.post(app.Apis.GET_DRUG_QUESTION,{
      userAnswerId: that.data.userAnswerId
      // consultDrugId:'4d1e56a10a8b4aedbcb939f7b6e0f07c',
      // // userId:app.userId,
      // userId:'111',
      // branchStoreId:'9990000',

    },result=>{
      console.log(result)
      that.data.drugId = result.data.consultDrug.id
      app.userId = result.data.consultDrugUserAnswer.userId
      app.branchStoreId = result.data.consultDrugUserAnswer.branchStoreId
      app.mainStoreId = result.data.consultDrugUserAnswer.mainStoreId
      that.setData({
        drugName: result.data.consultDrug.drugName
      })
      if (result.data.drugQuestionList.length>0){
        
        that.setData({
          all: result.data.drugQuestionList.length,
          
          // finished: options.id
        })
        that.setNewDataList(result.data.drugQuestionList)
      }

    })
  },
  
  chooseSubjectAction(e){
    console.log(e)
    let i = Number(e.detail.index)
    var d = this.data.done
    var p = this.data.progross
    var arr = JSON.parse(JSON.stringify(this.data.newSubjectData))
    // let arr = this.data.subjectData
    if (arr[i].model=='YYYY'){
      if (arr[i].content == '') {
        this.setData({
          done: d+1,
          progross:p+100/this.data.all
        })
      }
      this.data.newSubjectData[i].content = e.detail.data
      
    } else if (arr[i].model == 'RADIO'){
      var f = 0
      for (var j = 0; j < arr[i].data.length; j++) {
        if (arr[i].data[j].isSelected){
          f++
        }
      }
      if(f==0){
        this.setData({
          done: d + 1,
          progross: p + 100 / this.data.all
        })
      }
      this.data.newSubjectData[i].data = e.detail.data
    } else if (arr[i].model == 'SCALE'){
      console.log(arr[i].starNum)
      if (arr[i].starNum == 0) {
        this.setData({
          done: d + 1,
          progross: p + 100 / this.data.all
        })
      }
      this.data.newSubjectData[i].starNum = e.detail.data
    } else if (arr[i].model == 'TEXT'){
      this.data.newSubjectData[i].content = e.detail.data
      if (arr[i].content == '' && this.data.newSubjectData[i].content != '') {
        this.setData({
          done: d + 1,
          progross: p + 100 / this.data.all
        })
      } else if (arr[i].content != '' && this.data.newSubjectData[i].content == ''){
        this.setData({
          done: d - 1,
          progross: p - 100 / this.data.all
        })
      }
    }
    this.setData({
      disabled:this.data.done!=this.data.all
    })
  },

  // 点击提现
  clickTXAction(){
    this.data.isNeedSave = false
    wx.navigateTo({
      url: '/pages/myCoin/index',
    })
  },
  // 点击提交
  handleSubmit(){ 
    if(this.data.finished){
      return
    }
    var arr = this.data.newSubjectData
    var answer = []
    for (var i = 0; i < arr.length;i++){
      var subAnswer = {}
      subAnswer.questionId = arr[i].id
      if (arr[i].model=='RADIO'){
        var subData = arr[i].data
        var a = 0
        for(var j = 0;j<subData.length;j++){
          if (subData[j].isSelected){
            subAnswer.answer = subData[j].name
            a++
          }
        }
        if(a==0){
          this.srollTo(i)
          return
        }
      } else if (arr[i].model == 'YYYY') {
        if (arr[i].content==''){
          this.srollTo(i)
          return
        }else{
          subAnswer.answer = arr[i].content
        }
      } else if (arr[i].model == 'SCALE') {
        if (arr[i].starNum == 0) {
          this.srollTo(i)
          return
        } else {
          subAnswer.answer = String(arr[i].starNum)
        }
      } else if (arr[i].model == 'TEXT') {
        if (arr[i].content == '') {
          this.srollTo(i)
          return
        }else{
          subAnswer.answer = arr[i].content
        }
      } else if (arr[i].model == 'CHECK_BOX') {
        var subData = arr[i].data
        var a = 0
        var checkboxA = []
        for (var j = 0; j < subData.length; j++) {
          if (subData[j].isSelected) {
            checkboxA.push(subData[j].name)
            a++
          }
        }
        
        subAnswer.answer = JSON.stringify(checkboxA)
        if (a == 0) {
          this.srollTo(i)
          return
        }
      }
      answer.push(subAnswer)
    } 
    console.log(answer)
    var that = this
    app.post(app.Apis.POST_DRUG_ANSWER,{
      userAnswerId: that.data.userAnswerId,
      answerJsonStr: answer
    },result=>{
      console.log(result)
      if (result.success){
        that.data.isNeedSave = false
        wx.removeStorage({
          key: 'evaluateData',
          success: function (res) { },
        })
        wx.navigateTo({
          url: '/pages/getHealthCoin/index?scale=' + result.data,
        })
      }
    })
    // return
   
    
  },

  // 滑动到未完成的题目上
  srollTo(i){
    console.log(i)
    const query = wx.createSelectorQuery()
    query.select('#list-'+i).boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      wx.pageScrollTo({
        scrollTop: res[1].scrollTop + res[0].top - 100,
      })
    })
  },

   // 进度条展示
  checkProgress(){
    var index = 0
    for (var i = 0; i < this.data.newSubjectData.length;i++){
      let data = this.data.newSubjectData[i]
      let model = data.model
      if (model == 'RADIO' || model == 'CHECK_BOX'){
        var f = 0
        for (var j = 0; j < data.data.length; j++) {
          if (data.data[j].isSelected) {
            f++
          }
        }
        if (f != 0) {
          index++
        }
      } else if (model == 'SCALE'){
        if(data.starNum!=0){
          index++
        }
      } else if (model == 'YYYY') {
        if (data.content != '') {
          index++
        }
      }else{
        if (data.content != '') {
          index++
        }
      }
    }

    this.setData({
      done: index,
      progross: index*100 / this.data.all
    })
  },

  
  setNewDataList(arr){
    var newList = []
    for(var i = 0;i<arr.length;i++){
      var sub = arr[i]
      var ct = {}
      ct.title = sub.subject
      ct.id = sub.id
      ct.model = sub.type
      var list = []
      if (sub.optionList && sub.optionList.length>0){
        for (var j = 0; j < sub.optionList.length;j++){
          if (sub.type == 'CHECK_BOX'){
            let subInArr = JSON.parse(sub.answer)
            console.log(subInArr)
            let subIn = sub.optionList[j]
            var n = {}
            n.name = subIn
            n.isSelected = subInArr.indexOf(subIn) >= 0
            list.push(n)
          } else if (sub.type == 'RADIO'){
            let subIn = sub.optionList[j]
            var n = {}
            n.name = subIn
            n.isSelected = sub.answer == subIn
            list.push(n)
          }
          
        }
        
      }
      ct.data = list
      ct.content = sub.answer ? sub.answer : ''
      ct.starNum = sub.answer ? Number(sub.answer) : 0
      ct.tip = sub.optionList
      ct.placeholder = '请在此填写（最多100字）'
      newList.push(ct)
    }
    this.setData({
      newSubjectData: newList
    })
    this.checkProgress()
  },


  /**
   * 点击服务评价
  */
  clickServiceAction(){
    wx.navigateTo({
      url: '/pages/evaluatePaging/index',
    })
  },

  /**
   * 点击健康咨询
  */
  clickHealthEvaluateAction() {
    wx.navigateTo({
      url: '/pages/consultationHome/index',
    })
  }

})